package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductSorters;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 * 电商系统客户端
 * 通过网络连接与服务器通信
 */
public class EStoreClient {
    private final String serverHost;
    private final int serverPort;
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    // 用户系统
    private boolean isLoggedIn = false;
    private boolean isAdmin = false;
    private String currentUser = "";

    public EStoreClient(String host, int port) {
        this.serverHost = host;
        this.serverPort = port;
    }

    public void start() {
        showWelcome();

        while (true) {
            if (!isLoggedIn) {
                showLoginMenu();
            } else {
                if (isAdmin) {
                    showAdminMenu();
                } else {
                    showUserMenu();
                }
            }
        }
    }

    /**
     * 显示欢迎信息
     */
    private void showWelcome() {
        System.out.println("🎉 欢迎使用电商系统客户端!");
        System.out.println("🌐 服务器: " + serverHost + ":" + serverPort);
        System.out.println("=====================================");
    }

    /**
     * 登录菜单
     */
    private void showLoginMenu() {
        System.out.println("\n🔐 === 登录系统 ===");
        System.out.println("1. 用户登录");
        System.out.println("2. 管理员登录");
        System.out.println("3. 退出系统");
        System.out.print("请选择: ");

        int choice = readIntInput(1, 3);

        switch (choice) {
            case 1:
                userLogin();
                break;
            case 2:
                adminLogin();
                break;
            case 3:
                System.out.println("感谢使用，再见！");
                System.exit(0);
                break;
        }
    }

    /**
     * 用户登录
     */
    private void userLogin() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();

        if (username.isEmpty()) {
            System.out.println("❌ 用户名不能为空！");
            return;
        }

        // 简单的用户验证（实际项目中应该连接数据库）
        if (username.length() >= 3) {
            isLoggedIn = true;
            isAdmin = false;
            currentUser = username;
            System.out.println("✅ 用户 " + username + " 登录成功！");
        } else {
            System.out.println("❌ 用户名至少3个字符！");
        }
    }

    /**
     * 管理员登录
     */
    private void adminLogin() {
        System.out.print("请输入管理员账号: ");
        String adminName = scanner.nextLine().trim();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine().trim();

        // 简单的管理员验证（实际项目中应该加密验证）
        if ("admin".equals(adminName) && "admin123".equals(password)) {
            isLoggedIn = true;
            isAdmin = true;
            currentUser = "管理员";
            System.out.println("✅ 管理员登录成功！");
        } else {
            System.out.println("❌ 管理员账号或密码错误！");
        }
    }

    /**
     * 用户菜单
     */
    private void showUserMenu() {
        System.out.println("\n🛍️  === 用户菜单 (" + currentUser + ") ===");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 搜索商品");
        System.out.println("3. 查看有库存商品");
        System.out.println("4. 添加到购物车");
        System.out.println("5. 查看购物车");
        System.out.println("6. 结算");
        System.out.println("7. 退出登录");
        System.out.print("请选择: ");

        int choice = readIntInput(1, 7);

        switch (choice) {
            case 1:
                browseProducts();
                break;
            case 2:
                searchProducts();
                break;
            case 3:
                browseInStockProducts();
                break;
            case 4:
                addToCart();
                break;
            case 5:
                viewCart();
                break;
            case 6:
                checkout();
                break;
            case 7:
                logout();
                break;
        }
    }

    /**
     * 管理员菜单
     */
    private void showAdminMenu() {
        System.out.println("\n⚙️  === 管理员菜单 ===");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 系统信息");
        System.out.println("3. 备份数据");
        System.out.println("4. 恢复数据");
        System.out.println("5. 查看备份信息");
        System.out.println("6. 保存数据");
        System.out.println("7. 退出登录");
        System.out.print("请选择: ");

        int choice = readIntInput(1, 7);

        switch (choice) {
            case 1:
                browseProducts();
                break;
            case 2:
                showSystemInfo();
                break;
            case 3:
                backupData();
                break;
            case 4:
                restoreData();
                break;
            case 5:
                showBackupInfo();
                break;
            case 6:
                saveData();
                break;
            case 7:
                logout();
                break;
        }
    }

    /**
     * 发送请求到服务器并获取响应
     */
    private Object sendRequest(String command, Object... additionalData) {
        try (Socket socket = new Socket(serverHost, serverPort);
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {

            output.writeObject(command);
            output.flush();

            // 发送附加数据
            for (Object data : additionalData) {
                output.writeObject(data);
                output.flush();
            }

            // 读取响应
            return input.readObject();

        } catch (ConnectException e) {
            System.out.println("❌ 无法连接到服务器，请检查服务器是否启动");
            return "ERROR: Connection failed";
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("❌ 通信错误: " + e.getMessage());
            return "ERROR: " + e.getMessage();
        }
    }

    /**
     * 浏览商品
     */
    private void browseProducts() {
        System.out.println("\n📦 正在从服务器获取商品列表...");

        Object response = sendRequest("GET_ALL_PRODUCTS");

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> products = (List<Product>) response;

            if (products.isEmpty()) {
                System.out.println("😔 商店里还没有商品");
            } else {
                System.out.println("--- 商品列表 (共 " + products.size() + " 件) ---");
                products.forEach(System.out::println);
            }
        } else {
            System.out.println("❌ 获取商品列表失败: " + response);
        }
    }

/**
 * 搜索商品
 */
private void searchProducts() {
    System.out.print("🔍 请输入搜索关键词: ");
    String keyword = scanner.nextLine().trim();

    if (keyword.isEmpty()) {
        System.out.println("❌ 搜索关键词不能为空");
        return;
    }

    Object response = sendRequest("SEARCH_PRODUCTS", keyword);

    if (response instanceof List) {
        @SuppressWarnings("unchecked")
        List<Product> products = (List<Product>) response;

        if (products.isEmpty()) {
            System.out.println("🔍 未找到包含 '" + keyword + "' 的商品");
        } else {
            System.out.println("🔍 找到 " + products.size() + " 个相关商品:");
            products.forEach(System.out::println);
        }
    } else {
        System.out.println("❌ 搜索失败: " + response);
    }
}

    /**
     * 浏览有库存的商品
     */
    private void browseInStockProducts() {
        System.out.println("\n📦 正在获取有库存商品...");

        Object response = sendRequest("GET_IN_STOCK_PRODUCTS");

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> products = (List<Product>) response;

            if (products.isEmpty()) {
                System.out.println("😔 当前没有有库存的商品");
            } else {
                System.out.println("--- 有库存商品 (共 " + products.size() + " 件) ---");
                products.forEach(System.out::println);
            }
        } else {
            System.out.println("❌ 获取有库存商品失败: " + response);
        }
    }

    /**
     * 添加到购物车
     */
    private void addToCart() {
        System.out.print("请输入商品ID: ");
        String productId = scanner.nextLine().trim();

        // 先检查商品是否存在
        Object checkResponse = sendRequest("GET_PRODUCT_BY_ID", productId);
        if (!(checkResponse instanceof Product)) {
            System.out.println("❌ 商品不存在: " + checkResponse);
            return;
        }

        Product product = (Product) checkResponse;
        System.out.println("选中商品: " + product.getName() + " | 价格: ¥" + product.getPrice());

        System.out.print("请输入数量: ");
        int quantity = readIntInput(1, 100);

        // 检查库存
        Object stockResponse = sendRequest("ADD_TO_CART", productId, quantity);
        if (stockResponse instanceof String && ((String) stockResponse).startsWith("ERROR")) {
            System.out.println("❌ " + stockResponse);
            return;
        }

        // 添加到本地购物车
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("✅ 已添加到购物车: " + product.getName() + " × " + quantity);
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n🛒 === 我的购物车 ===");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Object response = sendRequest("GET_PRODUCT_BY_ID", entry.getKey());
            if (response instanceof Product) {
                Product product = (Product) response;
                double subtotal = product.getPrice() * entry.getValue();
                System.out.printf("%-20s | ¥%-8.2f × %-3d = ¥%.2f\n",
                        product.getName(), product.getPrice(), entry.getValue(), subtotal);
                total += subtotal;
            }
        }
        System.out.println("-----------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    /**
     * 结算
     */
    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("🛒 购物车为空");
            return;
        }

        viewCart();
        System.out.print("确认结算吗？(y/N): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            // 在实际项目中，这里应该调用服务器的结算接口
            // 现在只是清空本地购物车
            shoppingCart.clear();
            System.out.println("🎉 结算成功！感谢您的购买！");
        } else {
            System.out.println("取消结算");
        }
    }

    /**
     * 系统信息
     */
    private void showSystemInfo() {
        System.out.println("\n📊 === 系统信息 ===");

        Object countResponse = sendRequest("GET_PRODUCT_COUNT");
        Object backupResponse = sendRequest("GET_BACKUP_INFO");

        System.out.println("商品总数: " + countResponse);
        System.out.println("备份信息: " + backupResponse);
        System.out.println("服务器: " + serverHost + ":" + serverPort);
    }

    /**
     * 备份数据
     */
    private void backupData() {
        System.out.println("\n💾 正在备份数据...");
        Object response = sendRequest("BACKUP_DATA");
        System.out.println("备份结果: " + response);
    }

    /**
     * 恢复数据
     */
    private void restoreData() {
        System.out.println("\n🔄 正在恢复数据...");
        System.out.print("⚠️  警告：此操作将覆盖当前数据，确定继续吗？(y/N): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            Object response = sendRequest("RESTORE_DATA");
            System.out.println("恢复结果: " + response);
        } else {
            System.out.println("取消恢复操作");
        }
    }

    /**
     * 显示备份信息
     */
    private void showBackupInfo() {
        Object response = sendRequest("GET_BACKUP_INFO");
        System.out.println("\n📋 备份信息: " + response);
    }

    /**
     * 保存数据
     */
    private void saveData() {
        System.out.println("\n💾 正在保存数据...");
        Object response = sendRequest("SAVE_DATA");
        System.out.println("保存结果: " + response);
    }

    /**
     * 退出登录
     */
    private void logout() {
        isLoggedIn = false;
        isAdmin = false;
        currentUser = "";
        shoppingCart.clear();
        System.out.println("✅ 已退出登录");
    }

    /**
     * 读取整数输入
     */
    private int readIntInput(int min, int max) {
        while (true) {
            try {
                int input = scanner.nextInt();
                scanner.nextLine(); // 消费换行符

                if (input >= min && input <= max) {
                    return input;
                } else {
                    System.out.printf("❌ 请输入 %d 到 %d 之间的数字: ", min, max);
                }
            } catch (InputMismatchException e) {
                System.out.print("❌ 请输入有效的数字: ");
                scanner.nextLine(); // 清除无效输入
            }
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8888;

        if (args.length >= 2) {
            host = args[0];
            try {
                port = Integer.parseInt(args[1]);
            } catch (NumberFormatException e) {
                System.err.println("无效的端口号，使用默认端口 8888");
            }
        }

        EStoreClient client = new EStoreClient(host, port);
        client.start();
    }
}


